#include "GlobalExtractor.h"


void GlobalExtractor::update_info_aggregation(const vector<string>& forms, const vector<string>& tags)
{
	his_forms.push_back(forms);
	his_tags.push_back(tags);
}

void GlobalExtractor::update_info_label(const vector<string>& forms, const vector<string>& tags)
{
	for(int i = 0; i < (int)forms.size(); i++)
	{
		const string& cur_form = forms[i];
		const string& cur_tag  = tags[i];

		map<string,int>& label_count = string2label_count[cur_form];
		map<string,int>::iterator it = label_count.find(cur_tag);
		if( it == label_count.end() )
		{
			label_count[cur_tag] = 1;
		}
		else
		{
			it->second += 1;
		}
	}
}

void GlobalExtractor::extract_features_aggregation(const string& form, const string& tag, vector<string>& features)
{
	int count = 0;
	int his_idx = his_forms.size()-1;

	while(his_idx >=0 && count <= 200)
	{
		const vector<string>& his_forms_cur = his_forms[his_idx];
		const vector<string>& his_tags_cur  = his_tags[his_idx];

		for(int i=0; i<(int)his_forms_cur.size(); i++)
			if(his_forms_cur[i] == form && his_tags_cur[i] == tag)
			{
				vector<string> f_a_w;
				extract_window(his_forms_cur, i, f_a_w);
				features.insert(features.end(), f_a_w.begin(), f_a_w.end());
			}

		count += (int)his_forms_cur.size();
		his_idx -= 1;
	}
}

void GlobalExtractor::extract_features_label(const string& form, vector<string> &features)
{
	map<string,map<string,int> >::const_iterator cit_s2m = string2label_count.find(form);

	if(cit_s2m == string2label_count.end()) 
		return;

	const map<string,int>& label_count = cit_s2m->second;

	int max_count = -1;
	string max_key;

	for(map<string,int>::const_iterator cit = label_count.begin();
		cit != label_count.end();
		cit ++)
	{
		if(cit->second > max_count)
		{
			max_count = cit->second;
			max_key   = cit->first;
		}
	}

	features.push_back("MaxPrevTag="+max_key);
}

//////////////////////////////////

void GlobalExtractor::extract_window(const vector<string>& forms, int i, vector<string>& features)
{
	features.clear();

	string x_1 = (i >= 1) ? forms[i-1] : "<s>";
	features.push_back("x_1="+x_1);

	string x_2 = (i >= 2) ? forms[i-2] : "<s>";
	features.push_back("x_2="+x_2);

	string x0 = forms[i];
	features.push_back("x0="+x0);

	string x1 = (i < (int)forms.size()-1) ? forms[i+1] : "<t>";
	features.push_back("x1="+x1);

	string x2 = (i < (int)forms.size()-2) ? forms[i+2] : "<t>";
	features.push_back("x2="+x2);
}
